package com.zhunaer.service.impl;

import com.zhunaer.dao.OrderDao;
import com.zhunaer.dao.UserDao;
import com.zhunaer.entity.Order;
import com.zhunaer.utils.JDBCUtils;
import java.sql.Connection;
import java.sql.SQLException;

import com.zhunaer.service.OrderService;
import com.zhunaer.entity.User;
import com.zhunaer.entity.Room;
import java.math.BigDecimal;

public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao;

    @Override
    public int createOrder(User user, Room room, int quantity) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            JDBCUtils.beginTransaction(conn);
            
            Order order = new Order();
            order.setUserId(user.getUserId());
            order.setRoomId(room.getRoomId());
            order.setQuantity(quantity);
            order.setTotalAmount(room.getPrice().multiply(new BigDecimal(quantity)));
            
            int result = orderDao.createOrder(order);
            JDBCUtils.commitTransaction(conn);
            return result;
        } catch (SQLException e) {
            JDBCUtils.rollbackTransaction(conn);
            throw new RuntimeException("创建订单失败", e);
        } finally {
            JDBCUtils.close(conn, null, null);
        }
    }

    @Override
    public int cancelOrder(int orderId) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            JDBCUtils.beginTransaction(conn);
            int result = orderDao.updateOrderStatus(orderId, "CANCELED");
            JDBCUtils.commitTransaction(conn);
            return result;
        } catch (SQLException e) {
            JDBCUtils.rollbackTransaction(conn);
            throw new RuntimeException("取消订单失败", e);
        } finally {
            JDBCUtils.close(conn, null, null);
        }
    }
}